package com.suos.core.logic;


import com.suos.conf.SuOsProperties;
import com.suos.core.entity.SysInfo;
import com.suos.core.utils.PriUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * @author : MisShi
 * @date: 2021-10-22 15:57:08
 */
@Slf4j
@NoArgsConstructor
public class SugarClient implements Runnable {

    private SuOsProperties suOsProperties;

    private String inetHost;

    private int inetPort;

    private SysInfo sysInfo;

    public SugarClient(SuOsProperties suOsProperties, SysInfo sysInfo) {
        this.suOsProperties = suOsProperties;
        this.sysInfo = sysInfo;
        this.inetHost = PriUtil.getHost(suOsProperties.getRegisterUrl());
        this.inetPort = PriUtil.getPort(suOsProperties.getRegisterUrl());
    }

    public void start() throws Exception {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) {
                ch.pipeline().addLast(
                        new ObjectDecoder(1024 * 1024,
                                ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())),
                        new ObjectEncoder()
                );
                ch.pipeline().addLast(new SugarClientHandler(suOsProperties,sysInfo));
            }
        });
        bootstrap.remoteAddress(inetHost, inetPort);
        ChannelFuture future = bootstrap.connect().addListener(new ConnectionListener(suOsProperties, sysInfo));
        future.channel().closeFuture().sync();
    }

    @SneakyThrows
    @Override
    public void run() {
        this.start();
    }
}

